package com.qt.receiver;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qt.dispatcher.DisPatcher;
import com.qt.mapper.JudgeMapper;
import com.qt.pojo.dto.ToJudgeDTO;
import com.qt.pojo.entity.judge.Judge;
import com.qt.utils.Constants;
import com.qt.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author pgw
 * @version 1.0
 * @description
 * @date Create by 2023/9/26 16:30
 */
@Component
public class JudgeReceiver  extends  AbstractReceiver{

    @Autowired
    private  RedisUtil redisUtil;

    @Autowired
    private JudgeMapper judgeMapper;

    @Autowired
    private  DisPatcher dispatcher;

    @Async("judgeTaskAsyncPool")
    public void processWaitingTask() {
        // 优先处理比赛的提交任务
        // 其次处理普通提交的提交任务
        // 最后处理在线调试的任务
        handleWaitingTask(Constants.Queue.CONTEST_JUDGE_WAITING.getName(),
                Constants.Queue.GENERAL_JUDGE_WAITING.getName(),
                Constants.Queue.TEST_JUDGE_WAITING.getName());
    }

    @Override
    public String getTaskByReids(String queue) {
        if(redisUtil.lGetListSize(queue) > 0){
            return (String) redisUtil.lrPop(queue);
        }
        return null;
    }


    @Override
    public void handleJudgeTask(String taskStr, String queueName) {
       if(Constants.Queue.TEST_JUDGE_WAITING.getName().equals(queueName)){
           //自测
       }else{
           JSONObject task = JSONUtil.parseObj(taskStr);
           Long judgeId = task.getLong("judgeId");
           Judge judge = judgeMapper.selectById(judgeId);
           if(judge !=  null){

               //判断此次评测是否被取消
               if(1 == 0){
                   //取消

               }else{
                   String token = task.getStr("token");
                   // 调用判题服务
                   dispatcher.dispatch(Constants.TaskType.JUDGE, new ToJudgeDTO()
                           .setJudge(judge)
                           .setToken(token)
                   );
               }

           }
       }
//       processWaitingTask();

    }
}
